<template>
  <div class="sale_orer">
    <div style="display: none">
      <div id="qrcode2"></div>
    </div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            
            <a-col :span="6">
              <a-form-item label="查询条件">
                <a-input v-model="queryParam.orderParams" placeholder="请输入查询条件" allow-clear
                  @keyup.enter.native="handleQuery" />
              </a-form-item>
            </a-col>
            
            <a-col :span="6">
              <a-form-item label="单据阶段">
                <a-select placeholder="请选择状态" v-model="statusArr" style="width: 100%" allow-clear mode="multiple">
                  <a-select-option v-for="(d, index) in statusOptions" :key="index" :value="d.dictValue">{{
                    d.dictLabel
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="开单员">
                <a-input v-model.trim="queryParam.createByName" placeholder="请输入开单员姓名" allow-clear
                  @keyup.enter.native="handleQuery" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="业务员">
                <a-input v-model.trim="queryParam.customernanName" placeholder="请输入业务员姓名" allow-clear
                  @keyup.enter.native="handleQuery" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="测量员">
                <a-input v-model.trim="queryParam.billerName" placeholder="请输入测量员姓名" allow-clear
                  @keyup.enter.native="handleQuery" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="下单日期">
                <a-range-picker format="YYYY-MM-DD" v-model="orderDate"  :show-today="true"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="开单日期">
                <a-range-picker format="YYYY-MM-DD" v-model="receiveDate"  :show-today="true"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item >
                <a-checkbox v-model="showEndStatus" @change="statusChange" style="height:30px;line-height: 30px;">过滤已完成</a-checkbox>
              </a-form-item>
            </a-col>
            
          </a-row>
          <a-row :gutter="32">
            
            <a-col :span="6">
              <a-form-item label="安装日期">
                <a-range-picker format="YYYY-MM-DD" v-model="installDate"  :show-today="true"/>
              </a-form-item>
            </a-col>
            <!-- <a-col :span="6">
              <a-form-item label="电话" prop="phone">
                <a-input v-model="queryParam.phone" placeholder="请输入电话" allow-clear @keyup.enter.native="handleQuery" />
              </a-form-item>
            </a-col> -->
            <!-- <a-col :span="6">
              <a-form-item label="审核状态">
                <a-select placeholder="请选择状态" v-model="queryParam.auditStatus" style="width: 100%" allow-clear>
                  <a-select-option value="1">待审核</a-select-option>
                  <a-select-option value="2">已审核</a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->
            <a-col>
              <span class="table-page-search-submitButtons" style="float: right">
                <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
       <accessory-form v-if="showSetAccModal" ref="accessoryForm"
                                @close="showSetAccModal = false" @ok="accessOK"/>
       <biz-measure-form v-if="showMeasureModal" ref="bizMeasureForm" @close="showMeasureModal = false" @ok="measureOK"/>
                                
      <!-- 增加 -->
      <biz-order-add-form v-if="showAddModal" ref="bizOrderAddForm" :customerIdOptions="customerIdOptions"
        :deliveryOptions="deliveryOptions" :installOptions="installOptions"
        :isSettleSendOptions="isSettleSendOptions" :orderTypeOptions="orderTypeOptions" @ok="getList"
        :warehouseIdOptions="warehouseIdOptions" @close="showAddModal = false" />
      <!-- 查看 -->
      <biz-order-view-form v-if="showViewModal" :customerIdOptions="customerIdOptions" ref="bizOrderViewForm" @ok="getList" @close="showViewModal = false" />
      <!-- 生产 -->
      <biz-order-produce-form v-if="showProduceModal" ref="bizOrderProduceForm" @ok="getList" @close="showProduceModal = false" />
      <!-- 工序修改 -->
      <biz-order-produce-edit-form v-if="showProduceEditModal" ref="bizOrderProduceEditForm" @ok="getList" @close="showProduceEditModal = false" />
      <!-- 补单 -->
      <biz-order-supplement-form v-if="showSupplementModal" ref="bizOrderSupplementForm" :customerIdOptions="customerIdOptions"
        :isSettleSendOptions="isSettleSendOptions" :orderTypeOptions="orderTypeOptions" @ok="getList"
        @close="showSupplementModal = false" />
      <!-- 工序进度 -->
      <biz-order-record-form v-if="showRecordModal" ref="bizOrderRecordForm" @ok="getList"
        @close="showRecordModal = false" />
      <!-- 安装 -->
      <biz-order-install-form v-if="showInstallModal" ref="bizOrderInstallForm" @ok="getList" @close="showInstallModal = false" />
      <QRcodeForm v-if="showQRcode" ref="QRcode" ></QRcodeForm>
      <set-user ref="setUser" v-if="showSetUser" @ok="getList"></set-user>
      <!-- 费用修改 -->
      <OrderIndexForm ref="OrderIndexForm" @ok="getList"/>
      <advance-table
        class="sale_table"
        :customRow="customRow"
        :rowClassName="getRowClassName" 
        :scroll="{y:600}"
        :components="drag(columns)"
        title="销售单" :pagination="{
        current: queryParam.pageNum,
        pageSize: queryParam.pageSize,
        pageSizeOptions:pageSizeOptions,
        total: total,
        showSizeChanger: true,
        showLessItems: true,
        showQuickJumper: true,
        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
        onChange: changeSize,
        onShowSizeChange: onShowSizeChange,
      }" tableKey="base-bizOrder-index-table" rowKey="id" @refresh="getList" :columns="columns"
      @expandedRowsChange="expandedRowsChange"
      @expand="expand"
      :expandedRowKeys.sync="expandedRowKeys"
        :data-source="bizOrderList" :loading="loading" :format-conditions="true" @change="handleTableChange" :row-selection="{ selectedRowKeys: selectedRowKeys,getCheckboxProps:getCheckboxProps, onChange: onSelectChange,type:'radio' }">
         
        <div class="table-operations" slot="button">
          <a-button type="primary" @click="handleAdd({})" v-hasPermi="['biz:bizOrder:add']">
            <a-icon type="plus" />新增
          </a-button>
          <a-button type="primary"  @click='print'>
            <a-icon />打印
          </a-button>
          <a-button type="primary"  @click='exportExcel'>
            <a-icon />导出
          </a-button>
          <a-button type="primary" @click="showSupplement" v-hasPermi="['biz:bizOrder:spplement']">
           补单
          </a-button>
          <a-button type="primary" @click="handleProduceEdit" v-hasPermi="['biz:bizOrder:processEdit']">
           工序修改
          </a-button>
           <a-button :type="getAccessoryType" @click="setAccessory">
            配件信息
            </a-button>
           <a-button  @click="setMeasure" :type="getMeasureType">
            测量信息
            </a-button>
          <a-button type="primary" @click="printQcode">
            二维码
          </a-button>
        </div>
        
        <span slot="indexSlot" slot-scope="{ record,index }">
          {{record.id ? index + 1 :'合计'}}
        </span>
        <span slot="expandedRowRender" slot-scope="{ record,index }">
          <a-row :gutter="24">
            <a-col :span="16">
              <!-- <div style="display: none">
                <div id="qrcode2"></div>
              </div> -->
              <biz-order-product-index ref="BizOrderProductIndex" @selectProduct="selectProduct($event,index)" :expanedIndex="index" :orderId="record.id" :orderNumber="record.orderNumber" :tenantId="record.tenantId" :address="record.address"/>
              <biz-order-process-index ref="BizOrderProcessIndex" @processOk="processOk($event,record)" :orderId="record.id" :selectedInfo="record.selectedInfo"/>
            </a-col>
            <a-col :span="8">
              <biz-order-comment-index ref="BizOrderCommentIndex" :orderId="record.id" />
            </a-col>
          </a-row>
        </span>
        <span slot="projectSlot" slot-scope="{ record }">
          <span v-if="record.projectNumber">
            {{ record.projectNumber }}
          </span>
          <span v-else> -- </span>
        </span>
        <span slot="customerId" slot-scope="{ record }">
          {{ customerIdFormat(record) }}
        </span>
        <span slot="isSettleSend" slot-scope="{ record }">
          {{ isSettleSendFormat(record) }}
        </span>
        <span slot="orderType" slot-scope="{ record }">
          {{ orderTypeFormat(record) }}
        </span>
        <span slot="auditRender" slot-scope="{ record }">
          <span v-if="record.id">
            <span v-if="record.auditStatus == 1">待审核</span>
            <span v-else>已审核</span>
          </span>
        </span>
        <span slot="record" slot-scope="{ record }">
          <a @click="selectRecord(record)" v-if="record.id"> 工序进度 </a>
        </span>

        <span slot="sinkSlot" slot-scope="{ record }">
          <span v-if="record.sinkArrival" @click="handleSinkArrival(record, 0)"><a>水槽已到</a></span>
          <span v-else @click="handleSinkArrival(record, 1)" style="color: #0099cc"><a>水槽未到</a></span>
        </span>
        <span slot="statusRender" slot-scope="{ record }">
          {{ statusFormat(record) }}
        </span>
        <span slot="installType" slot-scope="{ record }">
          {{ installFormat(record) }}
        </span>
        <span slot="deliveryType" slot-scope="{ record }">
          {{ deliveryFormat(record) }}
        </span>
        <span slot="installer" slot-scope="{ record }">
          {{ getPerson(record,2) }}
        </span>
        <span slot="deliverier" slot-scope="{ record }">
          {{ getPerson(record,1) }}
        </span>
        <span slot="shippingStatus" slot-scope="{ record }">
          {{ shippingFormat(record) }}
        </span>
        
        <span slot="unCollectedAmount" slot-scope="{ record }">
          {{ $toDecimal(record.saleAmount - record.collectedAmount) }}
        </span>
        <span slot="saleMargin" slot-scope="{ record }">
          {{ $toDecimal(record.saleAmount - record.balance) }}
        </span>
        <span slot="totalFee" slot-scope="{ record }">
          {{ getTotalFee(record) }}
        </span>
        <span slot="profit" slot-scope="{ record }">
          {{$toDecimal(record.saleAmount - record.balance -  getTotalFee(record)) }}
        </span>
        <span slot="accessoryFileList" slot-scope="{ record }">
          
          <span v-if="record.id">
            <span v-if="record.accessoryFileList">有</span>
          <span v-else>无</span>
          </span>
        </span>
        
        <span slot="operation" slot-scope="{ record }">
          <!-- <a @click="handleView(record)" v-if="record.orderStatus > 1" v-hasPermi="['biz:bizOrder:edit']"> 查看 </a> -->
          <!-- <a @click="printQcode(record)">
            二维码
          </a> -->
          <!-- <a @click="handleUpdate(record)" v-if="record.orderStatus == 1" v-hasPermi="['biz:bizOrder:edit']"> 修改 </a> -->
          <!-- <a @click="handleSupplement(record)" v-if="record.orderStatus == 4" v-hasPermi="['biz:bizOrder:spplement']">补单</a> -->
          <!-- <a @click="audit(record, 2)" v-if="record.orderStatus == 1" v-hasPermi="['biz:bizOrder:edit']"> 审核 </a> -->
          <!-- <a @click="audit(record, 1)" v-if="record.orderStatus > 1" v-hasPermi="['biz:bizOrder:edit']">
            取消审核
          </a> -->
          <a-dropdown v-if="record.id">
            <a class="ant-dropdown-link" @click.prevent>
              更多操作
            </a>
            <template #overlay>
              <a-menu>
                <!-- <a-menu-item>
                  <a @click="handleDelete(record, 3)" v-hasPermi="['biz:bizOrder:remove']">删除</a>
                </a-menu-item> -->
                <a-menu-item v-if="record.orderStatus == 3">
                  <a @click="handleMaterial(record, 3)" v-hasPermi="['biz:bizOrder:edit']">领料</a>
                </a-menu-item>
                <a-menu-item v-if="record.orderStatus == 3">
                  <a @click="returnProcess(record, 3)" v-hasPermi="['biz:bizOrder:returnProcess']">取消生产</a>
                </a-menu-item>
                <a-menu-item v-if="record.orderStatus == 2">
                  <a @click="handleProduce(record)" v-hasPermi="['biz:bizOrder:edit']">下达生产</a>
                </a-menu-item>
                <!-- <a-menu-item>
                  <a @click="handleSupplement(record)" v-hasPermi="['biz:bizOrder:spplement']">补单</a>
                </a-menu-item> -->
                <a-menu-item v-if="record.orderStatus == 4">
                  <a @click="handleComplete(record, 6)" v-hasPermi="['biz:bizOrder:edit']">生产完成</a>
                </a-menu-item>
                <!-- <a-menu-item v-if="record.orderStatus == 5">
                  <a @click=" (record)" v-hasPermi="['biz:bizOrder:edit']">安装</a>
                </a-menu-item> -->
                <a-menu-item v-if="record.orderStatus == 5 && record.installType == 1 && record.deliveryType == 1">
                  <a @click="handleSuccess(record, 9)" v-if="record.orderStatus == 6" v-hasPermi="['biz:bizOrder:edit']">
                    发货完成
                  </a>
                </a-menu-item>
                <a-menu-item v-if="record.orderStatus == 7 && record.installType == 2 && record.deliveryType == 1">
                  <a @click="handleSuccess(record, 8)" v-hasPermi="['biz:bizOrder:edit']">
                    发货完成
                  </a>
                </a-menu-item>
                
                <a-menu-item v-if="['6','7'].includes(record.orderStatus) && (record.deliveryType == 2 || record.installType == 2)">
                  <a @click="handleInstaller(record, 8)" v-hasPermi="['biz:bizOrder:edit']">
                    派单
                  </a>
                </a-menu-item>
                <a-menu-item v-if="['7'].includes(record.orderStatus)">
                  <a @click="handleCompleteOrder(record, 8)" v-hasPermi="['biz:bizOrder:edit']">
                    订单完成
                  </a>
                </a-menu-item>
                <a-menu-item v-if="record.orderStatus == -1">
                  <a @click="handleError(record, -1)" v-hasPermi="['biz:bizOrder:edit']"> 订单异常 </a>
                </a-menu-item>
                <a-menu-item v-if="record.orderStatus < 8 && record.orderStatus > 1">
                  <a @click="handleEnd(record)" v-hasPermi="['biz:bizOrder:endOrder']">强制完成</a>
                </a-menu-item>
                <a-menu-item >
                  <a @click="handleEditFee(record)" v-hasPermi="['biz:bizOrder:feeEdit']">费用</a>
                </a-menu-item>

              </a-menu>
            </template>
          </a-dropdown>
        </span>
      </advance-table>
    </a-card>
    
    <ant-modal
      :visible="open"
      modal-title="打印销售订单"
      :adjust-size="true"
      @cancel="cancel"
      modalHeight="550"
      modalWidth="1000">
      <a-row slot="content">
        <iframe height='425' width='985' style='border:none;min-height: 100vh;width: 100%;' :src='setUrl' ></iframe>
      </a-row>
      <div slot="footer">
        <a-button @click="cancel">关闭</a-button>
      </div>
    </ant-modal>
  </div>
</template>
<script>
import { listBizOrder, delBizOrder, changeOrder, getInitData, auditOrder, sinkArrivalOrder, process,shipmentsStatus,returnProcess,completeOrder,orderPrintExcel,endOrder } from '@/api/biz/bizOrder'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import BizOrderAddForm from '@/views/biz/bizorder/modules/BizOrderAddForm.vue'
import BizOrderProduceForm from '@/views/biz/bizorder/modules/BizOrderProduceForm.vue'
import BizOrderProduceEditForm from '@/views/biz/bizorder/modules/BizOrderProduceEditForm.vue'
import BizOrderSupplementForm from '@/views/biz/bizorder/modules/BizOrderSupplementForm.vue'
import BizOrderRecordForm from '@/views/biz/bizorder/modules/BizOrderRecordForm.vue'
import BizOrderViewForm from '@/views/biz/bizorder/modules/BizOrderViewForm.vue'
import BizOrderInstallForm from '@/views/biz/bizorder/modules/BizOrderInstallForm.vue'
import SelectUser from '@/components/pt/selectUser/SelectUser'
import BizOrderProductIndex from '@/views/biz/bizorder/BizOrderProductIndex.vue'
import BizOrderCommentIndex from '@/views/biz/bizorder/BizOrderCommentIndex.vue'
import BizOrderProcessIndex from '@/views/biz/bizorder/BizOrderProcessIndex.vue'
import { listAllBizCustomer } from '@/api/biz/bizCustomer'
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
import AccessoryForm from '@/views/biz/bizorder/modules/AccessoryForm.vue'
import BizMeasureForm from '@/views/biz/bizorder/modules/BizMeasureForm.vue'
import QRcodeForm from '@/views/biz/bizorder/modules/QRcode.vue'
import QRCode from 'qrcodejs2';
import SetUser from '@/views/biz/bizorder/modules/SetUser';
import listMixin from '@/mixins/listMixin';
import { hasPermi } from '@/utils/util';
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import AntModal from '@/components/pt/dialog/AntModal'
import moment from 'moment';
import OrderIndexForm from './modules/OrderIndexForm';
import { toDecimal } from '@/utils/calculate'
import { mapGetters } from 'vuex'
export default {
  name: 'BizOrder',
  components: {
    AdvanceTable,
    BizOrderProduceForm,
    BizOrderProduceEditForm,
    BizOrderSupplementForm,
    BizOrderRecordForm,
    BizOrderViewForm,
    BizOrderInstallForm,
    BizOrderProductIndex,
    BizOrderCommentIndex,
    BizOrderProcessIndex,
    BizOrderAddForm,
    SelectUser,
    BizMeasureForm,
    AccessoryForm,
    QRcodeForm,
    SetUser,
    AntModal,
    OrderIndexForm 
  },
  mixins:[tableDragResizeMixin,listMixin],
  data() {
    return {
      setUrl:'',
      printUrl:'/api/biz/bizOrder/orderPrint?Authorization='+storage.get(ACCESS_TOKEN),
      open:false,
      showSetAccModal: false,
      showAddModal: false,
      showEditModal: false,
      showRecordModal: false,
      showInstallModal:false,
      showSupplementModal:false,
      showProduceModal:false,
      showProduceEditModal:false,
      showViewModal:false,
      showSetUser:false,
      disabledCreated:false,
      showQRcode:false,
      showMeasureModal:false,
      // 遮罩层
      loading: true,
      orderDate:undefined,
      receiveDate:undefined,
      installDate:undefined,
      createByNameObj:null,//开单员
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 销售单表格数据
      bizOrderList: [],
      // 客户字典
      customerIdOptions: [],
      // 清账发货字典
      isSettleSendOptions: [],
      // 订单类型字典
      orderTypeOptions: [],
      statusOptions: [],
      // 仓库
      warehouseIdOptions:[],
      // 配送模式
      deliveryOptions:[],
      // 安装模式
      installOptions:[],
      // 发货状态
      shippingOptions:[],
      // 查询状态
      statusArr:[],
      showEndStatus:true,
      // 展开的行
      expandedRowKeys:[],
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 11,
        orderNumber: undefined,
        phone: undefined,
        auditStatus: undefined,
        orderStatus: undefined,
        showEndStatus:1
      },
      
      pageSizeOptions: ['11', '21', '31', '101', '201'],
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'indexSlot' },
        },
        {
          title: '项目编号',
          dataIndex: 'projectNumber',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'projectSlot' },
        },
        {
          title: '订单编号',
          dataIndex: 'orderNumber',
          ellipsis: true,
          align: 'center',
          sorter:true,
        },
        {
          title: '客户',
          dataIndex: 'customerName',
          ellipsis: true,
          align: 'center',
          sorter:true,
        },
        {
          title: '部门',
          dataIndex: 'deptIdName',
          ellipsis: true,
          align: 'center',
          sorter:true,
        },
        {
          title: '下单日期',
          dataIndex: 'orderDate',
          ellipsis: true,
          align: 'center',
          sorter:true,
        },
        {
          title: '送货地址',
          dataIndex: 'address',
          ellipsis: true,
          align: 'center',
          sorter:true,
        },
        {
          title: '业主电话',
          dataIndex: 'phone',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '测量员',
          dataIndex: 'billerName',
          align: 'center',
          sorter:true,
        },
        {
          title: '开单员',
          dataIndex: 'createByName',
          align: 'center',
          // sorter:true,
        },
        {
          title: '业务员',
          dataIndex: 'customernanName',
          align: 'center',
        },
        {
          title: '开单日期',
          dataIndex: 'receiveDate',
          ellipsis: true,
          align: 'center',
          sorter:true,
        },
        {
          title: '安装日期',
          dataIndex: 'installDate',
          ellipsis: true,
          align: 'center',
          sorter:true,
        },
        {
          title: '工序进度',
          scopedSlots: { customRender: 'record' },
          align: 'center',
        },
        {
          title: '清账发货',
          dataIndex: 'isSettleSend',
          scopedSlots: { customRender: 'isSettleSend' },
          align: 'center',
          sorter:true,
        },
        {
          title: '成品位置',
          dataIndex: 'productWarehouse',
          align: 'center',
          sorter:true,
        },
        {
          title: '安装模式',
          dataIndex: 'installType',
          align: 'center',
          scopedSlots: { customRender: 'installType' },
        },
        {
          title: '配送模式',
          dataIndex: 'deliveryType',
          align: 'center',
          sorter:true,
          scopedSlots: { customRender: 'deliveryType' },
        },
        {
          title: '安装员',
          dataIndex: 'installerPerson',
          align: 'center',
        },
        {
          title: '配送员',
          dataIndex: 'deliveryPerson',
          align: 'center',
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          scopedSlots: { customRender: 'orderType' },
          align: 'center',
          sorter:true,
        },
        {
          title: '销售金额',
          dataIndex: 'saleAmount',
          ellipsis: true,
          align: 'center',
          sorter:true,
        },
        {
          title: '收款金额',
          dataIndex: 'collectedAmount',
          ellipsis: true,
          align: 'center',
          sorter:true,
        },
        {
          title: '未收金额',
          dataIndex: 'unCollectedAmount',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'unCollectedAmount' },
          customRender:(t,r,index)=>{
            return this.$toDecimal(r.saleAmount - r.collectedAmount)
          }
        },
        {
          title: '库存成本',
          dataIndex: 'balance',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '销售毛利',
          ellipsis: true,
          dataIndex: 'saleMargin',
          align: 'center',
          scopedSlots: { customRender: 'saleMargin' },
        },
        {
          title: '费用合计',
          ellipsis: true,
          align: 'center',
          dataIndex:'totalFee',
          scopedSlots: { customRender: 'totalFee' },
        },
        {
          title: '净利润',
          ellipsis: true,
          align: 'center',
          dataIndex:'profit',
          scopedSlots: { customRender: 'profit' },
        },
        {
          title: '配件信息',
          dataIndex: 'accessoryFileList',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'accessoryFileList' },
        },
        {
          title: '审核状态',
          dataIndex: 'auditStatus',
          align: 'center',
          scopedSlots: { customRender: 'auditRender' },
        },
        {
          title: '发货状态',
          dataIndex: 'shippingStatus',
          align: 'center',
          scopedSlots: { customRender: 'shippingStatus' },
        },
        {
          title: '单据阶段',
          dataIndex: 'orderStatus',
          align: 'center',
          scopedSlots: { customRender: 'statusRender' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'operation' },
          fixed:'right'
        },
      ],
    }
  },
  created() {
    // 没有权限干掉列
    if(!this.hasPermi('biz:bizOrder:price_show')){
      let hideColumns = 'collectedAmount,saleAmount,unCollectedAmount'
      this.columns = this.columns.filter(v=>!hideColumns.includes(v.dataIndex))
    }
    // 费用修改
    if(!this.hasPermi('biz:bizOrder:feeEdit')){
      let hideColumns1 = 'balance,saleMargin,profit,totalFee'
      this.columns = this.columns.filter(v=>!hideColumns1.includes(v.dataIndex))
    }
    setTimeout(()=>{
      this.initColumnsSetting()
    },200)
    // 默认开单时间
    let endTime = moment(new Date())
    let startTime = moment(new Date()).subtract(90, "days")
    this.receiveDate = [startTime,endTime]
    this.getList()
    getInitData('order_type,sys_yes_no,order_status,install_type,delivery_type,shipping_status').then((response) => {
      this.isSettleSendOptions = response.data.sys_yes_no
      this.orderTypeOptions = response.data.order_type
      this.statusOptions = (response.data.order_status || []).filter(v=>!(['8'].includes(v.dictValue)) )
      this.deliveryOptions = response.data.delivery_type
      this.installOptions = response.data.install_type
      this.shippingOptions = response.data.shipping_status
    })
    listAllBizCustomer().then((response) => {
      this.customerIdOptions = response.data
    })

    // allListBizWarehouse().then(response => {
    //   this.warehouseIdOptions = response.data
    // })
  },
  computed: {
    getAccessoryType() {
      if(this.selectedRows.length){
        let data = this.selectedRows[0]
        if(data.accessoryFileList){
          return 'success'
        }else{
          return 'warnning'
        }
      }
      return 'primary'
    },
    getMeasureType() {
      if(this.selectedRows.length){
        let data = this.selectedRows[0]
        if(data.measureId){
          return 'success'
        }else{
          return 'warnning'
        }
      }
      return 'primary'
    },
    
    ...mapGetters([
      'tenantInfo'
    ])
  },
  methods: {
    
    /**
     * @排序
     * @param {obj} pagination 
     * @param {*} filters 
     * @param {*} sorter 
     */
     handleTableChange (pagination, filters, sorter) {
      
      if (sorter.field !== undefined && sorter.field !== null && sorter.field !== '') {
        if(sorter.field === 'customerName'){
          this.queryParam.orderByColumn = 'bc.' + sorter.field
        }else if(sorter.field === 'createByName'){
          this.queryParam.orderByColumn = 'su.name'
        }else if(sorter.field === 'billerName'){
          this.queryParam.orderByColumn = 'u.name'
        }else{
          this.queryParam.orderByColumn = 'a.' + sorter.field
        }

        this.queryParam.isAsc = sorter.order
      }
      this.getList()
    },
    hasPermi,
    /** 查询销售单列表 */
    getList() {
      this.selectedRows = [];
      this.selectedRowKeys = []
      this.loading = true
      if(this.statusArr && this.statusArr.length){
        this.queryParam.orderStatus = this.statusArr.join(',')
      }else{
        delete this.queryParam.orderStatus
      }
      
      if(this.orderDate && this.orderDate.length>0) {
        this.queryParam.startDate=this.orderDate[0].format('yyyy-MM-DD');
      } else {
        this.queryParam.startDate=undefined;
      }
      if(this.orderDate && this.orderDate.length>1) {
        this.queryParam.endDate = this.orderDate[1].format('yyyy-MM-DD');
      } else {
        this.queryParam.endDate=undefined;
      }
      // 开单日期
      if(this.receiveDate && this.receiveDate.length>0) {
        this.queryParam.beginReceiveDate=this.receiveDate[0].format('yyyy-MM-DD');
      } else {
        this.queryParam.beginReceiveDate=undefined;
      }
      if(this.receiveDate && this.receiveDate.length>1) {
        this.queryParam.endReceiveDate = this.receiveDate[1].format('yyyy-MM-DD');
      } else {
        this.queryParam.endReceiveDate=undefined;
      }
      
      // 安装日期
      if(this.installDate && this.installDate.length>0) {
        this.queryParam.beginInstallDate=this.installDate[0].format('yyyy-MM-DD');
      } else {
        this.queryParam.beginInstallDate=undefined;
      }
      if(this.installDate && this.installDate.length>1) {
        this.queryParam.endInstallDate = this.installDate[1].format('yyyy-MM-DD');
      } else {
        this.queryParam.endInstallDate=undefined;
      }
      let param = this.getQueryParam()
      listBizOrder(param).then((response) => {
        this.bizOrderList = response.data.list
        this.total = response.data.total
        this.loading = false
        this.tableAddTotalRow(this.columns,this.bizOrderList)
      }).catch(()=>{
        this.loading = false
      })
    },
    getQueryParam(){
      return Object.assign({},this.queryParam,{pageSize:this.queryParam.pageSize - 1})
    },
    statusChange(e){
      if(e.target.checked){
        this.queryParam.showEndStatus = 1
      }else{
        delete this.queryParam.showEndStatus
      }
      this.getList()
    },
    audit(row, status) {
      var that = this
      this.$confirm({
        title: '确认审核所选中数据?',
        onOk() {
          return auditOrder(row.id, status).then(() => {
            that.getList()
            that.$message.success('操作成功', 3)
          })
        },
        onCancel() { },
      })
    },
    handleMaterial(row, status) {
      var that = this
      this.$confirm({
        title: '确认领料?',
        onOk() {
          return changeOrder(row.id, status).then(() => {
            that.getList()
            that.$message.success('操作成功', 3)
          })
        },
        onCancel() { },
      })
    },
    /**
     * 取消生产
     * @param {obj} row 
     * @param {string | number} status 
     */
    returnProcess(row, status) {
      var that = this
      this.$confirm({
        title: '确认取消生产?',
        onOk() {
          return returnProcess({id:row.id}).then(() => {
            that.getList()
            that.$message.success('操作成功', 3)
          })
        },
        onCancel() { },
      })
    },
    /**
     * 设置table的row的class
     * @param {obj} row 
     * @param {number} index 
     */
    getRowClassName(row,index){
      if (row.addressRepetition) {
        return 'multiple_table_row'
      }
    },
    handleComplete(row, status) {
      var that = this
      this.$confirm({
        title: '确认生产完成?',
        onOk() {
          return changeOrder(row.id, status).then(() => {
            that.getList()
            that.$message.success('操作成功', 3)
          })
        },
        onCancel() { },
      })
    },
    handleCompleteOrder(row, status){
      var that = this
      this.$confirm({
          title: '确认完成订单?',
          onOk() {
            return completeOrder({id:row.id}).then(() => {
              that.getList()
              that.$message.success('操作成功', 3)
            })
          },
          onCancel() { },
        })
    },
    handleSuccess(row, status) {
      var that = this
      this.$confirm({
        title: '确认完成订单?',
        onOk() {
          return changeOrder(row.id, status).then(() => {
            shipmentsStatus({id:row.id,shippingStatus:1}).then(res=>{
              if(res.code == 200) {
                that.getList()
                that.$message.success('操作成功', 3)
               }else{
                 this.message.error(res.msg)
               }
            }).catch((err)=>{
                 console.log('err >>',err) 
            })
          })
        },
        onCancel() { },
      })
    },
    handleInstaller(row) {
      this.showSetUser = true
      this.$nextTick(()=>{
        this.$refs.setUser.title = '分配派送'
        this.$refs.setUser.handleSetUser(row)
      })
    },   
     setAccessory() {
          if(this.selectedRows.length == 0) {
            this.$message.warn('请选择销售单据');
            return;
          }
          if(this.selectedRows.length > 1) {
            this.$message.warn('只能选择一条销售单据');
            return;
          }
          this.showSetAccModal=true;

          this.$nextTick(()=>{
            this.$refs.accessoryForm.handleSetAccessory(this.selectedRows[0]);
          }) 
        },
        setMeasure() {
          if(this.selectedRows.length == 0) {
            this.$message.warn('请选择销售单据');
            return;
          }
          if(this.selectedRows.length > 1) {
            this.$message.warn('只能选择一条销售单据');
            return;
          }
          this.showMeasureModal = true;
          this.$nextTick(()=>{
            this.$refs.bizMeasureForm.handleSetMeasure(this.selectedRows[0]);
          }) 
        },
        
        accessOK(){
          this.selectedRows = [];
          this.selectedRowKeys = []
          this.getList()
        },
        measureOK(){
          this.selectedRows = [];
          this.selectedRowKeys = []
          this.getList()
        },
        showSupplement() {
          if(this.selectedRows.length == 0) {
            this.$message.warn('请选择销售单据');
            return;
          }
          if(this.selectedRows.length > 1) {
            this.$message.warn('只能选择一条销售单据');
            return;
          }
          this.handleSupplement(this.selectedRows[0])
        },
        printQcode() {
          if(this.selectedRows.length == 0) {
            this.$message.warn('请选择销售单据');
            return;
          }
          if(this.selectedRows.length > 1) {
            this.$message.warn('只能选择一条销售单据');
            return;
          }
          if(this.selectedRows[0].auditStatus == 1) {
            this.$message.warn('单据未审核');
            return;
          }
            let printContent = ``;
            // 租户宝利发不要订单编号
            if (this.tenantInfo && this.tenantInfo.tenantId === '1e48ae6b19c44ec88d68c8ed2748b0da') {
              printContent = `
            <div style="display:flex">
              <div style="text-align: center;margin:0 0 10px;border:1px solid #000;padding:10px;width:270px;font-weight:bold;" id='XQ'></div>
              <div style="margin-left:30px;font-size:30px;font-weight:bold;">
                <div><label style="font-weight:bold;">客户地址：</label><span style="font-size:30px;font-weight:bold;">${this.selectedRows[0].address}</span></div>
              </div>  
            </div>`
              
            }else{
              printContent = `
            <div style="display:flex">
              <div style="text-align: center;margin:0 0 10px;border:1px solid #000;padding:10px;width:270px"fount-" id='XQ'></div>
              <div style="margin-left:30px;font-size:30px;font-weight:bold;">
                <div><label style="font-weight:bold;">订单编号：</label><span style="font-size:30px;font-weight:bold;">${this.selectedRows[0].orderNumber}</span></div>
                <div><label style="font-weight:bold;">客户地址：</label><span style="font-size:30px;font-weight:bold;">${this.selectedRows[0].address}</span></div>
              </div>  
            </div>`
            }
            
            this.handleQRcode(printContent)
            
        },
    handleError(row, status) {
      var that = this
      this.$confirm({
        title: '确认订单异常?',
        onOk() {
          return changeOrder(row.id, status).then(() => {
            that.getList()
            that.$message.success('操作成功', 3)
          })
        },
        onCancel() { },
      })
    },
    handleEnd(row) {
      var that = this
      this.$confirm({
        title: '确认强制完成订单?',
        onOk() {
          return endOrder(row.id).then(() => {
            that.getList()
            that.$message.success('操作成功', 3)
          })
        },
        onCancel() { },
      })
    },
    expand(expand,record){
      this.selectRecord(record)
      
      //  解决Ant Design Vue table组件固定某列(fixed)和展开某行(expandedRowRender)不能同时使用
      this.$nextTick(() => {
        setTimeout(() => {
          const element = document.querySelectorAll(`[data-row-key='${record.id}-extra-row']`)
          // 计算需要展开高度， 采用append dom元素的方式撑开高度，直接修改高度，
          // 但是当前行触发moursemove事件 会触发dom style 重置
          // 33 是td 的 padding 值 加 border值
          const height = element[0].getBoundingClientRect().height - 33
          console.log('height :>> ', height);
          element[1].childNodes[0].innerHTML = `<div style="height: ${height}px;"></div>`
        },100)
      })
    },
    expandOk(expand,record){
      //  解决Ant Design Vue table组件固定某列(fixed)和展开某行(expandedRowRender)不能同时使用
      this.$nextTick(() => {
        setTimeout(() => {
          const element = document.querySelectorAll(`[data-row-key='${record.id}-extra-row']`)
          // 计算需要展开高度， 采用append dom元素的方式撑开高度，直接修改高度，
          // 但是当前行触发moursemove事件 会触发dom style 重置
          // 33 是td 的 padding 值 加 border值
          const height = element[0].getBoundingClientRect().height - 33
          console.log('height :>> ', height);
          element[1].childNodes[0].innerHTML = `<div style="height: ${height}px;"></div>`
        },100)
      })
    },
    expandedRowsChange(arr){
      
    },
    handleSinkArrival(row, status) {
      var that = this
      row.flag = status
      var txt = status == 1 ? '确认水槽已到?' : '确认水槽未到?'
      this.$confirm({
        title: txt,
        onOk() {
          return sinkArrivalOrder(row).then(() => {
            that.getList()
            that.$message.success('操作成功', 3)
          })
        },
        onCancel() { },
      })
    },
    handleInstall(row) {
      this.showInstallModal = true
      let data = { id: row.id }
      this.$nextTick(() => {
        this.$refs.bizOrderInstallForm.handleInstall(data)
      })
    },
    handleQRcode(data) {
      this.showQRcode = true
      this.$nextTick(() => {
        this.$refs.QRcode.show(this.selectedRows,data)
      })
    },
    selectRecord(record) {
      if(this.expandedRowKeys.length && record.id === this.expandedRowKeys[0]){
        this.expandedRowKeys = []
      }else{
        this.expandedRowKeys = [record.id]
      }
    },
    handleProduce(record) {
      // var txt = '确认下达生产?'
      // this.$confirm({
      //   title: txt,
      //   onOk:()=>{
      //     process({id:record.id}).then(() => {
      //       this.getList()
      //       this.$message.success('操作成功', 3)
      //     })
      //   },
      //   onCancel() { },
      // })
      this.showProduceModal = true
      this.$nextTick(()=>{
        this.$refs.bizOrderProduceForm.handleProduce(record)
      })
    },
    handleProduceEdit() {
      
      if(this.selectedRows.length !== 1) {
            this.$message.warn('请选择一条销售单据');
            return;
          }
      this.showProduceEditModal = true
      this.$nextTick(()=>{
        this.$refs.bizOrderProduceEditForm.handleProduceEdit(this.selectedRows[0])
      })
    },
    
    // 客户字典翻译
    customerIdFormat(row) {
      if (row.customerId) {
        return this.selectDictLabel(this.customerIdOptions, row.customerId)
      } else {
        return ''
      }
    },
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.orderStatus)
    },
    // 配送模式
    deliveryFormat(row) {
      return this.selectDictLabel(this.deliveryOptions, row.deliveryType)
    },
    shippingFormat(row) {
      return this.selectDictLabel(this.shippingOptions, row.shippingStatus)
    },
    // 安装模式
    installFormat(row) {
      return this.selectDictLabel(this.installOptions, row.installType)
    },
    // 清账发货字典翻译
    isSettleSendFormat(row) {
      if (row.isSettleSend) {
        return this.selectDictLabel(this.isSettleSendOptions, row.isSettleSend)
      } else {
        return ''
      }
    },
    // 订单类型字典翻译
    orderTypeFormat(row) {
      if (row.orderType) {
        return this.selectDictLabel(this.orderTypeOptions, row.orderType)
      } else {
        return ''
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        orderNumber: undefined,
        customerId: undefined,
      }
      this.handleQuery()
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = size
      this.getList()
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleAdd(record) {
      this.showAddModal = true
      this.$nextTick(() => this.$refs.bizOrderAddForm.handleAdd(record))
    },
    handleUpdate(record) {
      this.showAddModal = true
      this.$nextTick(() => this.$refs.bizOrderAddForm.handleEdit(record))
    },
    handleView(record) {
      this.showAddModal = true
      this.$nextTick(() => this.$refs.bizOrderAddForm.handleView(record))
    },
    handleSupplement(record) {
      this.showSupplementModal = true
      this.$nextTick(() => this.$refs.bizOrderSupplementForm.handleSupplement(record))
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk() {
          return delBizOrder(row.id).then(() => {
            that.onSelectChange([], [])
            that.getList()
            that.$message.success('删除成功', 3)
          })
        },
        onCancel() { },
      })
    },
    selectProduct(e,index){
      let item = this.bizOrderList[index]
      item.selectedInfo = e
      this.bizOrderList.splice(index,1,item)
      this.expandOk(false,item)
    },
    processOk(e,record){
      this.expandOk(false,record)
    },
    /**
     * 
     * @param {obj} record 
     * @param {number} type 
     */
    getPerson(record,type){
      let bizOrderInstallers = record.bizOrderInstallers || []
      let result = bizOrderInstallers.filter(v=>+v.installerType == type)
      if(result.length) return result[0].installerUserName
      return ''
    },
    
    print() {
      let param = {}
      if(this.selectedRows.length){
        param = {
          id:this.selectedRows[0].id
        }
      }else{
        return this.$message.error('请选择一条数据')
      }
      this.setUrl =  this.printUrl + '&id='+ param.id
      this.open=true;
    },
    
    /** 导出按钮操作 */
    exportExcel () {
      var that = this,param
      if(this.selectedRows.length){
        param = {
          id:this.selectedRows[0].id
        }
      }else{
        return this.$message.error('请选择一条数据')
      }
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk () {
          return orderPrintExcel(param)
            .then(response => {
              that.download(response.msg)
              that.$message.success(
                '导出成功',
                3
              )
          })
        },
        onCancel () {}
      })
    },
    cancel(){
      this.open = false
    },
    getTotalFee(record){
      
      let total = 0
            for (let i = 1; i < 11; i++) {
              total += record[`cost${i}`]
            }
      return this.$toDecimal(total)
    },
    handleEditFee(record){
      this.$refs.OrderIndexForm.handleEdit(record)
    },
    customRow (record) {
        return {
          on: {
            dblclick: () => {
              this.$nextTick(() => {
                if(record.id){
                  this.handleView(record)
                }
              })
            }
          }
        }
      }
  },
}
</script>
<style type="text/css" scoped>
.ant-btn-success.ant-btn {
  border-color: #67c23a;
  background-color: #67c23a;
  color: #fff;
}
  .ant-btn-warnning.ant-btn {
    border-color: #ebb563;
    background-color: #ebb563;
    color: #fff;
}

</style>

<style type="text/css">
.multiple_table_row{
    background-color: #ed9090;
    /* color: white; */
  }
  .multiple_table_row:hover{
    color: inherit;
  }
   .ant-table-body{
    max-height: 600px;
    overflow-y:scroll;
  }
</style>